library(ggplot2)
library(tidyverse)
library(ggtext)
library(ggalluvial)


df <- read.csv("brex19.csv")
is_alluvia_form(as.data.frame(df), axes = 1:3, silent = TRUE)

colors <- c("Leave" = "grey10", "Remain" = "grey65")

plot2 <- ggplot(as.data.frame(df),
       aes(y = Percentage, axis1 = Brexit, axis2 = Party)) +
  geom_alluvium(aes(fill = Brexit), width = 1/12) +
  scale_fill_manual(values = colors) +
  geom_stratum(width = 4/12, fill = c("yellow", "#0066CC", 
                                      "white", "red", "blue")) +
  scale_x_discrete(limits = c("2016 EU\nreferendum", "2019 general\nelection"), 
                   expand = c(.05, .05)) +
  theme_bw() +
  theme(legend.position="none", axis.text.x=element_text(size=rel(1.5), 
                                                         color="black"),
        axis.title=element_text(size=rel(0.8))) +
  geom_label(stat = "stratum", aes(label = after_stat(stratum)))
plot2


df <- read.csv("brex15.csv")
is_alluvia_form(as.data.frame(df), axes = 1:3, silent = TRUE)

colors <- c("Leave" = "grey10", "Remain" = "grey65")

plot1 <- ggplot(as.data.frame(df),
                aes(y = Percentage, axis1 = Party, axis2 = Brexit)) +
  geom_alluvium(aes(fill = Brexit), width = 1/12) +
  scale_fill_manual(values = colors) +
  geom_stratum(width = 4/12, fill = c("white", "red", "blue",
                                      "yellow", "#0066CC")) +
  scale_x_discrete(limits = c("2015 general \nelection", "2016 EU\nreferendum"), 
                   expand = c(.05, .05)) +
  theme_bw() +
  theme(legend.position="none", axis.text.x=element_text(size=rel(1.5), 
                                                         color="black"),
        axis.title=element_text(size=rel(0.8))) +
  geom_label(stat = "stratum", aes(label = after_stat(stratum))) 
plot1

ggsave("flow2015.pdf",
       plot=plot1,
       width=149*0.8,
       height=210*0.8,
       units="mm")

ggsave("flow2019.pdf",
       plot=plot2,
       width=149*0.8,
       height=210*0.8,
       units="mm")

library(ggpubr)
ggarrange(
  plot1, plot2,
  common.legend = TRUE, legend = "bottom"
)

combined <- ggarrange(plot1 + rremove("ylab") , 
          plot2 + rremove("ylab"))

both <- annotate_figure(combined, left = text_grob("Percentage", 
                                        rot = 90, vjust = 1),
                fig.lab.size = 0.2)

ggsave("fig1.tiff", 
       width = 297*0.8, 
       height = 210*0.8, 
       units="mm",
       device='tiff', 
       dpi=700)

ggsave("both.pdf",
       plot=both,
       width=297*0.8,
       height=210*0.8,
       units="mm")

